package com.hundsun.cprs.yyt.web.action.upload;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.jresplus.common.util.StringUtil;
import com.hundsun.network.uc.biz.enums.EnumFileType;
import com.hundsun.network.uc.biz.util.helper.FileHelper;


@Controller
@RequestMapping("/goods")
public class UploadController extends BaseAction {
	
	@Value("${image.server.host}")
	private String serverHost;
	
	@Value("${image.server.port}")
	private String serverPort;
	
	@Value("${image.server.path}")
	private String uploadServerPath;
	
	@Value("${upload.images.root}")
	private String uploadPath;
	
	@Value("${upload.file.maxsize}")
	private String uploadFileMaxsize;
	
	@Value("${img.upload.compress:true}")
	private boolean imgUploadCompress;

	/**
	 * kindeditor富文本编辑器上传
	 * @author tanhl
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = { "/kindeditor-image-upload", "/kindeditor-accessory-upload" })
	public void kindeditorUpload(@RequestParam("imgFile") MultipartFile file,
                                 HttpServletRequest request, HttpServletResponse response) {
		String errMsg;
		//文件格式、大小校验
		if(StringUtil.equals(request.getRequestURI(), "/goods/kindeditor-image-upload.htm")) {
			errMsg = FileHelper.checkFile(file, EnumFileType.IMAGE.getCode());
		} else {
			errMsg = FileHelper.checkFile(file, EnumFileType.ACCESSORY.getCode());
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append("{");
		//如果文件格式校验没有错误则上传文件到服务器
		if(StringUtil.isBlank(errMsg)) {
			String uploadServer = "http://" + serverHost + ":" +serverPort + "/" + uploadServerPath;
			String uploadName = FileHelper.uploadFile(file, uploadPath);
			buffer.append("\"filename\":\"" + uploadName + "\""); // 上传之后的文件名
			buffer.append(",");
			buffer.append("\"fileOriginalName\":\"" + file.getOriginalFilename() + "\""); // 原始文件名
			buffer.append(",");
			buffer.append("\"url\":\"" + uploadServer + "/" + uploadName + "\""); // 上传之后的读取url
			buffer.append(",");
			buffer.append("\"error\":" + 0); // 上传之后的读取url
		} else {
			buffer.append("\"error\":" + 1);
			buffer.append(",");
			buffer.append("\"message\":\"" + errMsg + "\""); //如果有错误，返回错误信息
		}
		buffer.append("}");
		try {
			response.getWriter().write(buffer.toString());
			response.getWriter().close();
		} catch (Exception e) {
			log.error("富文本编辑器上传文件失败", e);
		}
	}
	
	@RequestMapping("download_file")
	public String download_file(HttpServletRequest request, 
			HttpServletResponse response, ModelMap model) {
		String filePath = filterBadStrs(request.getParameter("filePath"));
		String fileName = filterBadStrs(request.getParameter("fileName"));
		if(StringUtil.isBlank(uploadPath) 
				|| StringUtil.isBlank(filePath)
				|| StringUtil.isBlank(fileName)) {
			log.error("下载文件失败： 没有配置上传路径");
			return null;
		}
		//added on 20151008 start 去除链接中传参的上一层目录
		if(filePath.indexOf(FileHelper.LINUX_PARENT_DIR) != -1) {
			filePath = filePath.replace(FileHelper.LINUX_PARENT_DIR, "");
		}
		//added on 20151008 end
		if(!uploadPath.endsWith(FileHelper.SEP)) {
			uploadPath = uploadPath + FileHelper.SEP;
		}
		String fullPath = uploadPath + filePath;
		// 读到流中
		try {
			//fileName = URLDecoder.decode(fileName, "utf-8");
			InputStream inStream = new FileInputStream(fullPath);// 文件的存放路径
			// 设置输出的格式
			response.reset();
			response.setContentType("bin");
			response.setHeader("Content-Disposition", "attachment; filename=\""+ new String(fileName.getBytes("GBK"), "iso8859-1") + "\"");
			// 循环取出流中的数据
			byte[] b = new byte[100];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (Exception e) {
			log.error("下载文件失败", e);
			model.addAttribute("message", "下载文件失败:"+e.getMessage());
			return "error";
		}
		return null;
	}
	
	private String filterBadStrs(String str) {
		if(StringUtil.isBlank(str)) {
			return str;
		}
		return str.replaceAll("\r", "").replaceAll("\n", "").replaceAll("http", "").replaceAll("HTTP", "");
	}
	
	/**
	 * 附件公共ajax上传组件
	 * @param request
	 * @param response
	 * @param objName input file域的 name属性
	 * @author tanhl
	 */
   	@RequestMapping("upload_file")
	public @ResponseBody
	void uploadImage(MultipartHttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "objName") String objName) {
		try {
			MultipartFile file = request.getFile(objName);
			StringBuffer sbf = new StringBuffer();
			sbf.append("{");
			if (file != null) {
				// 检验文件类型以及大小
				long maxSize = StringUtil.isNotBlank(uploadFileMaxsize) 
						? Long.valueOf(uploadFileMaxsize) : FileHelper.MAX_FILE_SIZE; 
				String msg = FileHelper.checkFile(file, null, maxSize/8);
				if (StringUtil.isNotBlank(msg)) {
					sbf.append("error:");
					//对空格、加号的处理
					// sbf.append(msg);
					String str = URLEncoder.encode(msg, "utf-8");
					str = str.replace("+", "%20");
					sbf.append("'" + str + "'");
				} else {
					String accessUrl = null;
					if(imgUploadCompress) {
						accessUrl = FileHelper.uploadCompressFile(file, uploadPath);
					} else {
						accessUrl = FileHelper.uploadFile(file, uploadPath);
					}
					sbf.append("accessUrl:");
					sbf.append("'" + accessUrl + "'");
					sbf.append(",");
					sbf.append("fileSize:");
					sbf.append("'" + file.getSize() + "'");
				}
			}
			sbf.append("}");
			response.getWriter().write(sbf.toString());
	        response.getWriter().close();
		} catch (Exception e) {
			log.error(e);
		}
	}
}

